package com.hcbd.tdwt.ui.setting.xingyu.activity;

import android.annotation.SuppressLint;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;


import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.BaseActivity;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.ConvertToBdMsgTool;
import com.hcbd.tdwt.util.DateUtils;
import com.hcbd.tdwt.util.SharedPreferencesUtil;
import com.pangu.bdsdk2021.entity.terminalthree.BDSXXInfo;
import com.hcbd.tdwt.base.bd.XYSerialPortManage;
import com.hcbd.tdwt.ui.xingyu.vo.BoxContact;
import com.hcbd.tdwt.ui.xingyu.vo.UserMessageVO;
import com.hcbd.tdwt.ui.setting.xingyu.adapter.AutoTestAdapter;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;



import static java.lang.Thread.sleep;

@SuppressLint("NonConstantResourceId")
@EActivity(R.layout.activity_auto_test)
public class AutoTestActivity extends BaseActivity {
    @ViewById(R.id.set_message_number_et)
    EditText setMessageNumberEt;
    @ViewById(R.id.send_number_tv)
    TextView sendNumberTv;
    @ViewById(R.id.receive_number_tv)
    TextView receiveNumberTv;
    @ViewById(R.id.success_rate_tv)
    TextView successRateTv;
    @ViewById(R.id.recipient_tv)
    EditText recipientTv;
    @ViewById(R.id.start_test_btn)
    Button startTestBtn;
    @ViewById(R.id.stop_test_btn)
    Button stopTestBtn;
    @ViewById(R.id.send_content_et)
    EditText sendContentEt;
    @ViewById(R.id.log_rv)
    RecyclerView logRv;
    @ViewById(R.id.connect_box_img)
    ImageView connectBoxImg;
    //连接终端文本
    @ViewById(R.id.connect_box_tv)
    TextView connectBoxTv;
    //信号图标
    @ViewById(R.id.signal_icon)
    ImageView signalIcon;
    //连接布局
    @ViewById(R.id.connect_box_layout)
    LinearLayout connectBoxLayout;
    //信号布局
    @ViewById(R.id.signal_layout)
    RelativeLayout signalLayout;
    @ViewById(R.id.clear_log_btn)
    Button clear_log_btn;
    @ViewById(R.id.already_send_content)
    TextView alreadySendContent;
    /*    @ViewById(R.id.toolbar_return_arrow_img)
        ImageView toolbar_return_arrow_img;*/
    // 选择的电文形式按钮
    @ViewById(R.id.mode_ch)
    View selectModeBtn;

    @ViewById(R.id.send_freq)
    EditText sendFre;
    @ViewById
    RelativeLayout toobar;
    @ViewById
    ImageButton headLeft;
    @ViewById
    TextView title;
    private SharedPreferencesUtil sp;
    private AutoTestAdapter autoTestAdapter;
    private List<String> logList;
    //是否刷新终端信息
    private boolean isRefreshing = false;
    private boolean isStartTest=false;
    private Timer timer ;
    private int sendIndex=0;
    private int receiveIndex=0;
    public final int refreshData=2;
    private String msg;
    // 选择的电文形式
    private int mode = 1;
    private int sentWaitSec = 0;

    @AfterViews
    protected void init() {
        initMsgRegister();
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        ringtone= RingtoneManager.getRingtone(getApplicationContext(), notification);
        toobar.setBackground(getDrawable(R.color.lightGreen));
        title.setText("收发测试");
        headLeft.setBackground(getDrawable(R.drawable.left_while_arrow));
        sp=new SharedPreferencesUtil(this);
        logList=new ArrayList<>();
        initAutoTestAdapter();
        autoRefresh();
        setRecipientTv();

    }

    @Click
    void headLeft(){
        finish();
    }

    public void initAutoTestAdapter(){
        if(autoTestAdapter==null){
            autoTestAdapter=new AutoTestAdapter(this,logList);
        }else{
            autoTestAdapter.notifyDataSetChanged(logList);
            return;
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL,false);
        linearLayoutManager.setStackFromEnd(true);
        logRv.setLayoutManager(linearLayoutManager);
        logRv.setAdapter(autoTestAdapter);

    }

    /**
     * 刷新UI
     */
    @SuppressLint("HandlerLeak")
    private final Handler adapterHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    refreshStatus();
                    break;
                case 2:
                    String cardNumber=msg.getData().getString("cardNumber");
                    String content=msg.getData().getString("content");
                    sendIndex+=1;
                    sendNumberTv.setText(String.valueOf(sendIndex));
                    probabilityOfSuccess();
                    String str="已发送-- "+cardNumber+":"+content+"  时间: "+ DateUtils.getSysDate();
                    logList.add(str);
                    initAutoTestAdapter();
                    break;
            }
        }
    };
    public void probabilityOfSuccess(){
        if(sendIndex==receiveIndex){
            successRateTv.setText("100%");
        }else if(sendIndex>receiveIndex){
            float min=((float) receiveIndex/(float)sendIndex)*100;
            successRateTv.setText(MessageFormat.format("{0}%",  min));
        }
    }
    /**
     * 自动刷新
     */
    private void autoRefresh() {
        if (isRefreshing) {
            return;
        }
        isRefreshing = true;
        new Thread(() -> {
            try {
                while (isRefreshing) {
                    Message msg = new Message();
                    msg.what = 1;
                    adapterHandler.sendMessage(msg);
                    if (sentWaitSec > 0) sentWaitSec--;
                    sleep(1000);
                }
            } catch (Exception e) {
                Log.e("InfoMessage", e.toString());
            }
        }).start();
    }
    public void startTest(){
        if(sentWaitSec>0){
            toast("请等待频度足够再次点击测试！还差："+sentWaitSec+"s");
            return;
        }
        String str=setMessageNumberEt.getText().toString();
        if("".equals(str)){
            toast("请输入设定发送数量！");
            return;
        }
        final int number = Integer.parseInt(str);
        if(number==0||0>number){
            toast(msg);
            return;
        }
        final String recipient=recipientTv.getText().toString();
        if("".equals(recipient)){
            toast("请输入收件人！");
            return;
        }
        sendIndex=0;
        sendNumberTv.setText(String.valueOf(receiveIndex));
        receiveIndex=0;
        receiveNumberTv.setText(String.valueOf(receiveIndex));
        isStartTest=true;
        startTestBtn.setBackgroundColor(getResources().getColor(R.color.dimgray));
        stopTestBtn.setBackgroundColor(getResources().getColor(R.color.light_blue));
        timer=new Timer();
        final int freq = Integer.parseInt(sendFre.getText().toString());
        sentWaitSec = freq;
        timer.schedule(new TimerTask() {
            int index=0;
            @Override
            public void run() {
                sentWaitSec = freq;
                sendMessage(recipient);
                index+=1;
                if(index>=number||!BeidouBoxParams.isBoxConnectNormal){
                    stopTest();
                }
            }
        }, 0,(freq)* 1000);
    }
    public void stopTest(){
        if(isStartTest){
            isStartTest=false;
            startTestBtn.setBackgroundColor(getResources().getColor(R.color.light_blue));
            stopTestBtn.setBackgroundColor(getResources().getColor(R.color.dimgray));
            timer.cancel();
            timer=null;
        }else{
            toast("未开启测试！");
        }
    }
    public void sendMessage(String cardNumber){
        String content=sendContentEt.getText().toString();
        if("".equals(content)){
            content="一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十";
        }
        sendBdMsg(cardNumber,content);
        Message message=new Message();
        Bundle bundle=new Bundle();
        bundle.putString("content",content);
        bundle.putString("cardNumber",cardNumber);
        message.setData(bundle);
        message.what=refreshData;
        adapterHandler.sendMessage(message);
    }

    //发送消息
    void sendBdMsg(String targetNumber,String content){
        UserMessageVO userMessage = new UserMessageVO();
        userMessage.setSendTime(DateUtils.getDateLongSerial());
        userMessage.setSendNumber(BeidouBoxParams.userCardNumber);
        userMessage.setReceiverNumber(targetNumber);
        userMessage.setMsgType(Constant.TEXT);
        userMessage.setSeconds(0);
        userMessage.setContent(content);
        userMessage.setIoType(Constant.SEND_MESSAGE);
        userMessage.setRead(true);
        userMessage.setStatus(Constant.SEND_MSG_WAIT);
        String bdMsg;
        if(mode==1){
            bdMsg=content;
        }else if(mode==2){
            bdMsg = ConvertToBdMsgTool.castUserMessageTo0x90(userMessage);
        }else{
            bdMsg = ConvertToBdMsgTool.castUserMessageToA4(userMessage,false);
        }
        userMessage.insert();
        int frePoint = BeidouBoxParams.card_model==2? 1:2;
        XYSerialPortManage.getInstance().onPackageThroughCCTCQ(mode,frePoint,targetNumber,bdMsg);
        MainApp.getInstance().startNewSentWaitSecTimer();
        runOnUiThread(() -> MainApp.getInstance().startSentStatusWaitSecTimer());

        BeidouBoxParams.lastMsg=userMessage;
        BoxContact.cacheFromBoxId(targetNumber,Constant.TEXT,content,true);


        sp.addAttribute(Constant.LAST_SEND_BD_MSG_NUM, targetNumber);

    }



    /**
     * 刷新终端信息
     */
    private void refreshStatus() {
        if (BeidouBoxParams.isBoxConnectNormal) {
            connectBoxImg.setImageResource(R.drawable.connect_box_icon);
            if (BeidouBoxParams.userCardNumber == null) {
                connectBoxTv.setText("");
            } else {
                connectBoxTv.setText(MessageFormat.format("{0}{1}", getResources().getString(R.string.beidou_mobile_phone), BeidouBoxParams.userCardNumber));
            }
            alreadySendContent.setText("距离下一次发送时间:"+sentWaitSec);
            connectBoxLayout.setBackground(getResources().getDrawable(R.drawable.clickable_oval_pink));
            int bdSignal = BeidouBoxParams.getBdSignal();

            if (bdSignal == 0) {
                signalIcon.setImageResource(R.drawable.signal1);
            } else if (bdSignal == 1) {
                signalIcon.setImageResource(R.drawable.signal2);
            } else if (bdSignal == 2) {
                signalIcon.setImageResource(R.drawable.signal3);
            } else if (bdSignal == 3) {
                signalIcon.setImageResource(R.drawable.signal4);
            } else {
                signalIcon.setImageResource(R.drawable.signal5);
            }
            signalLayout.setVisibility(View.VISIBLE);
        } else {
            connectBoxImg.setImageResource(R.drawable.unconnect_box_icon);
            connectBoxTv.setText(R.string.unconnect_box_detail);
            connectBoxLayout.setBackground(getResources().getDrawable(R.drawable.clickable_oval_pink));
            signalIcon.setImageResource(R.drawable.signal0);
            signalLayout.setVisibility(View.GONE);
        }
    }
    @Click
    void connect_box_layout(){
        if (BeidouBoxParams.isBoxConnectNormal) {
            showOldProtocolDialog("是否关闭北斗服务？", (dialog, confirm) -> {
                if (confirm) {
                    XYSerialPortManage.getInstance().closeXYSerialPort();
                }
                dialog.dismiss();
            });
        } else {
            XYSerialPortManage.getInstance().openXYSerialPort();
        }
    }
    @Click
    void  start_test_btn(){
        if(!BeidouBoxParams.isBoxConnectNormal) {
            toast("请打开串口！");
            return;
        }
        if(!isStartTest){
            startTest();
        }else{
            toast("已开始测试,请勿重复点击！");
        }
    }
    @Click
    void stop_test_btn(){
        if(!BeidouBoxParams.isBoxConnectNormal) {
            toast("请打开串口！");
            return;
        }else{
            toast("已关闭测试,请勿重复点击！");
        }
        stopTest();
    }
    @Click
    void clear_log_btn(){
        logList.clear();
        initAutoTestAdapter();
    }

    public void onMode(View view){
        mode = Integer.parseInt((String)view.getTag());
        selectModeBtn.setBackgroundResource(R.color.dimgray);
        selectModeBtn = view;
        selectModeBtn.setBackgroundResource(R.color.light_blue);
    }
    private Ringtone ringtone;

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void eventBus(UserMessageVO userMessage){
        ringtone.play();
        receiveIndex+=1;
        receiveNumberTv.setText(String.valueOf(receiveIndex));
        String str="接收到:"+userMessage.getReceiverNumber()+" :"+userMessage.getContent()+"  时间: "+ DateUtils.getSysDate();
        logList.add(str);
        initAutoTestAdapter();
        probabilityOfSuccess();

    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(String bleContent){
        refreshStatus();
    }
    /*   @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
        public void eventBus(BDICInfo bdicInfo){
         //   refreshStatus();
            setRecipientTv();
        }*/
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(BDSXXInfo bdsxxInfo){
        refreshStatus();
        setRecipientTv();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTest();
    }
    public void setRecipientTv(){
        String str=recipientTv.getText().toString();
        if("".equals(str)){
            if(BeidouBoxParams.userCardNumber!=null){
                recipientTv.setText(BeidouBoxParams.userCardNumber);
            }
        }
    }

}
